import api from "../../apis/activity"
import formApi from "../../apis/forms"

function formatDate(_date: string) {
  const date = new Date(_date)
  const weekdays = ["日", "一", "二", "三", "四", "五", "六"];

  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const weekday = weekdays[date.getDay()];
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");

  return `${year}.${month}.${day}周${weekday} ${hours}:${minutes}`;
}


let loadActivity = (that: PageTy, id: number) => {
  //load content
  api.getActivityContent(id).then(data => {
    that.setData({
      nodes: data,
    })
  })
  formApi.isSignUp(id).then(
    res => that.setData({
      isSignUp: res,
    })
  )
  // load details
  api.getActivityDetail(id).then(data => {
    that.setData({
      name: data["name"],
      deadline: new Date(data["deadline"]).getTime(),
      publisher: data["publisher_name"],
      activityDetailLayout: [
        { ...that.data.activityDetailLayout[0], content: formatDate(data["activity_time"]) },
        { ...that.data.activityDetailLayout[1], content: formatDate(data["deadline"]) },
        { ...that.data.activityDetailLayout[2], content: data["location"] ?? "未知" },
        { ...that.data.activityDetailLayout[3], content: data["additional_conditions"] ?? "不限" },
        { ...that.data.activityDetailLayout[4], content: data["limit"] ?? "不限" },
      ]
      // 'activityDetailLayout[0].content': formatDate(data["activity_time"]),
      // 'activityDetailLayout[1].content': formatDate(data["deadline"]),
      // 'activityDetailLayout[2].content': data["location"] ?? "未知",
      // 'activityDetailLayout[3].content': data["additional_conditions"] ?? "不限",
      // 'activityDetailLayout[4].content': data["limit"] ?? "不限",
    })
  }).catch(() => setTimeout(() => wx.navigateBack(), 2000));
}

let loadAnnouncement = async (that: PageTy, id: number) => {
  const data = await api.getAnnouncementContent(id)
  that.setData({
    nodes: data,
  })
  // load details
  const detail = await api.getAnnouncementDetail(id);
  console.log(detail);
  that.setData({
    announcementLayout: {
      name: detail["name"] ?? "暂无",
      publisher: detail["publisher_name"] ?? "未知",
      avatar: detail["publisher_avatar"] ?? "",
    }
  })
  console.log(that.data.announcementLayout)
}

interface PageDataTy {
  id: number;
  name: string;
  announcementLayout: {
    name: string;
    avatar: string;
    publisher: string;
  };
  activityDetailLayout: {
    icon: string;
    title: string;
    content: string;
  }[];
  isSignUp: boolean;
  deadline: number;
  publisher: string;
  nodes: string;
  variant: string;
  poster: string;
}

type PageTy = WechatMiniprogram.Page.Instance<PageDataTy, Record<string, any>>;

Page<PageDataTy, any>({
  data: {
    id: -1,
    name: "未知",
    announcementLayout: {
      name: "暂无",
      avatar: null,
      publisher: "未知"
    },
    activityDetailLayout: [
      { icon: "calendar", title: "活动时间", content: "未知" },
      { icon: "hourglass", title: "报名截至", content: "未知" },
      { icon: "location", title: "活动地点", content: "未知" },
      { icon: "filter", title: "其他条件", content: "不限" },
      { icon: "people", title: "活动人数", content: "不限" }
    ],
    isSignUp: false,
    deadline: new Date().getTime(),
    publisher: "",
    nodes: "<div style='text-align: center;'>暂无数据</div>",
    variant: "",
    poster: "",
  },
  signup: function (e) {
    wx.navigateTo({
      url: `/pages/signup/index?id=${this.data.id}`
    })
  },
  genShare() {
    const title = this.data.variant === "announcement" ? this.data.announcementLayout["name"] : this.data.name;
    return {
      title: title,
      imageUrl: this.data.poster,
      query: `id=${this.data.id}&variant=${this.data.variant}&poster=${this.data.poster}`,
    };
  },
  onShareTimeline(res) {
    return this.genShare();
  },
  onShareAppMessage(res) {
    return this.genShare();
  },
  async toSuccess() {
    const image = await formApi.getSuccessImage(this.data.id);
    console.log(image);
    wx.navigateTo({
      url: `/pages/success/index?backLevel=2${image != null ? `&image=${image}` : ""}`
    })
  },
  onLoad: async function (options: { 
    scene: string,
    id: number,
    variant: 'activity' | 'announcement',
    poster: string,
  }) {
    // id=${id}&variant=${variant}&poster=${image}
    const scene = decodeURIComponent(options.scene);
    // 此处清洗scene, 并保存数据到options里
    if (!scene) {
      let params = scene.split("&");
      console.log(params)
      // params error
      if (params.length < 2) {
        wx.showToast({
          title: '错误的二维码',
          icon: 'error',
          duration: 2000
        })
        setTimeout(() => wx.switchTab({
          url: '/pages/home/index',
        }), 2000);
      }
      options["variant"] = params[0] === "y" ? "activity" : "announcement";
      options["id"] = parseInt(params[1]);

      try {
        let poster;
        if (options["variant"] === "activity") {
          poster = await api.getActivityPoster(options["id"]);
        } else if (options["variant"] === "announcement") {
          poster = await api.getAnnouncementPoster(options["id"]);
        }
        console.log("poster " + poster);
        options["poster"] = poster ?? "/assets/poster.png";
      } catch (e) {
        options["poster"] = "/assets/poster.png";
      }
    }
    // 清洗结束，准备跳转
    const id = options["id"];
    this.setData({
      variant: options["variant"] ?? "",
      id: id,
      poster: options["poster"] ?? "/assets/poster.png",
    })
    switch (this.data.variant) {
      case "activity":
        loadActivity(this, id);
        break;
      case "announcement":
        loadAnnouncement(this, id);
        break;
    }
  }
});
